package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.Utility;
import com.ideabove.adapter.FolderAdapter;
import com.ideabove.data.Folder;
import com.ideabove.data.PlayItem;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.radio.module.SongSearchMd.BackToWhere;
import com.ideabove.radio.service.PlayBackService;
import com.ideabove.util.ConnectThread;
import com.ideabove.util.img.ImageLoader;
import com.tekle.oss.android.animation.AnimationFactory;
import com.tekle.oss.android.animation.AnimationFactory.FlipDirection;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.PorterDuff.Mode;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class FolderMd extends ModuleAbs{
	FolderMd mFolderMd;
	ArrayList<Folder> mFolderArr;
	
	public void init(final MainActivity activity){
		super.init(activity);
		mFolderMd = this;
	}
	
	public class UserRequestListener extends BaseRequestListener {

		@Override
		public void onComplete(final String response, final Object state) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(response);

//				Log.e("###jsonObject##", "#####" + jsonObject.toString());
				final String fbPicUrl = jsonObject.getJSONObject("picture")
						.getJSONObject("data").getString("url");
//				final String name = jsonObject.getString("name");
				Utility.userUID = jsonObject.getString("id");
				
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE ); 
				SharedPreferences.Editor editor = prefs.edit();					
				editor.putString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, fbPicUrl);
				editor.commit();
				
				activity.runOnUiThread(new Runnable() {
				   public void run() {
					   ImageView user_folder_pic = (ImageView)activity.findViewById(R.id.user_folder_pic);
					   ImageLoader.download(fbPicUrl, user_folder_pic);
				   }
				});



//				ImageView user_folder_pic = (ImageView)activity.findViewById(R.id.user_folder_pic);
//				ImageLoader.download(fbPicUrl, user_folder_pic);

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}
	
	public void playAllFolderSong(){
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();
				
				
				if(result != null && ((ArrayList)result).size() > 0){
					Toast.makeText(activity.getApplicationContext(), "스튜디오의 전곡이 플레이 됩니다\n" +
							"잠시만 기다려 주세요\n(Like 폴더제외)", Toast.LENGTH_LONG).show();
					
					hide();
					
					Message msg = Message.obtain(null, PlayBackService.REQUEST_MSG_GET_ALL_FOLDER_TO_PLAY);
					msg.obj = result;
					activity.sendMessageToService(msg);
				}else{
					Toast.makeText(activity.getApplicationContext(), "폴더에 모아 놓은 곡들이 없습니다.\n" +
							"선곡하기 버튼을 눌러주세요", Toast.LENGTH_LONG).show();
				}
				
			}
			
			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);					

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/playAll.php");
//					uId : 유저 ID

				String userId = activity.facebookMd.getBonoUserId();
				
				if(userId == null || userId.length() < 1){
					throw new Exception("parameter error");
				}
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", userId));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);
				
//				"result": [{
//			        "folder_id": "87",
//			        "cpost_id": "3760",
//			        "title": "\uc2e0\ub098\ub294 \uc12c - \ub9dd\uc6d0\ub3d9 \ub85c\ub9c8\ub2c8",
//			        "link": "DewJAzjeTmY",
//			        "thumb_url": "http:\/\/i.ytimg.com\/vi\/DewJAzjeTmY\/mqdefault.jpg",
//			        "user_id": "11",
//			        "isLikeIdx": "0"
//			    }
				
				
				if(jsonStr != null && jsonStr.length() > 0){

					ArrayList<PlayItem> playList = new ArrayList<PlayItem>();
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");
					
					for (int i = 0; i < resultArray.length(); i++) { 
						PlayItem pitem = new PlayItem();

						pitem.setCpost_id(resultArray.getJSONObject(i).getString("cpost_id").toString());
						pitem.setTitle(resultArray.getJSONObject(i).getString("title").toString());
						pitem.setLink(resultArray.getJSONObject(i).getString("link").toString());
						pitem.setThumbUrl(resultArray.getJSONObject(i).getString("thumb_url").toString());
						pitem.setLikeCnt(resultArray.getJSONObject(i).getString("isLikeIdx").toString());
						pitem.setpUid(activity.facebookMd.getBonoUserId());
						playList.add(pitem);
					}

					resultSet.setResult(playList);	
				}
				
			}
		}).start(); 
	}
	
	// 폴더아이디로 폴더 찾기
	public Folder getFolderById(String id){
		if(mFolderArr != null && id != null){
			for(Folder folder: mFolderArr){
				if(id.equals(folder.getFolder_id())){
					return folder;
				}
			}
		}
		return null;
	}
	
	public void showFolderList(){
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		
		
		LayoutInflater layoutInflater = (LayoutInflater) 
        activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_folders, null);
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert); 
		
		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {
			
			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
				ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
				ab.setPositiveButton("ok", null);  
				ab.show();
			}
			
			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();		
				
				SharedPreferences prefs = activity.getSharedPreferences(FacebookMd.PREFERENCE_USER_KEY, Activity.MODE_PRIVATE);
				String fbPicUrl 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_PIC_URL, "");
				String fbFirstNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_FIRST_NM, "");
				String fbLastNm 	= prefs.getString(FacebookMd.PREFERENCE_USER_FB_LAST_NM, "");
				String clubName 	= prefs.getString(FacebookMd.PREFERENCE_USER_CLUB_NAME, "");
				
				// 사진이 없다면...
				if(fbPicUrl == null || fbPicUrl.length() < 1){
					Utility.mFacebook = new Facebook(FacebookMd.APP_ID);
					Utility.mAsyncRunner = new AsyncFacebookRunner(Utility.mFacebook);		
				
					Bundle params = new Bundle();
					params.putString(Facebook.TOKEN, Session.getActiveSession().getAccessToken());
					params.putString("fields", "name, picture, email");
					Utility.mAsyncRunner.request("me", params, new UserRequestListener());
				}
				
				ImageView user_folder_pic = (ImageView)activity.findViewById(R.id.user_folder_pic);
				ImageLoader.download(fbPicUrl, user_folder_pic);	
				
				TextView user_name = (TextView)activity.findViewById(R.id.folder_user_name);
				user_name.setText(fbFirstNm + " " + fbLastNm);
				
				
//				Log.e("######", "###clubName###clubName#" + clubName);
				TextView folder_club_name = (TextView)activity.findViewById(R.id.folder_club_name);
				folder_club_name.setText(clubName);
				
				TextView btn_top_right_text = (TextView)activity.findViewById(R.id.btn_top_right_text);
				btn_top_right_text.setText("Radio");
				btn_top_right_text.setTextColor(activity.getResources().getColor(R.color.yellow));
				
				
				
				// 선곡하기 클릭				
				ImageView folder_btn_listen_each = (ImageView)activity.findViewById(R.id.folder_btn_listen_each);
				folder_btn_listen_each.setOnTouchListener(new OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							// 선곡하기를 보여준다 빽했을때 다시 이리루 호출함.
							activity.songSearchMd.showSongSearch(new BackToWhere() {
								
								@Override
								public void goBack() {
									// TODO Auto-generated method stub
									showFolderList();
								}
							});
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				// 라디오  가기 버튼(오른쪽 상단)
				ImageView btn_top_right_img = (ImageView)activity.findViewById(R.id.btn_top_right_img);
				btn_top_right_img.setOnTouchListener(new OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							activity.genreMd.showGenreList();
							
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
								
				FrameLayout btn_top_left_btn_wrap = (FrameLayout)activity.findViewById(R.id.btn_top_left_btn_wrap);
				btn_top_left_btn_wrap.setVisibility(View.VISIBLE);
				
				View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
				btn_top_right_btn_wrap.setVisibility(View.VISIBLE);
				
				

				// 편집 버튼 클릭
				ImageView btn_top_left_img = (ImageView)activity.findViewById(R.id.btn_top_left_img);
				btn_top_left_img.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						
						Log.e("onTouch", "onTouch");
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							activity.folderEditMd.showFolderEditList(null);
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return false;
					}
				});
				

				// 모두듣기 버튼 클릭
				ImageView folder_btn_listen_all = (ImageView)activity.findViewById(R.id.folder_btn_listen_all);
				folder_btn_listen_all.setOnTouchListener(new View.OnTouchListener() {
					
					@Override
					public boolean onTouch(View v, MotionEvent event) {
						// TODO Auto-generated method stub
						ImageView view = (ImageView)v;
						if(event.getAction() == MotionEvent.ACTION_DOWN){
							view.setPadding(2, 2, 2, 2);
							view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
						}else if(event.getAction() == MotionEvent.ACTION_UP){
							
							
							playAllFolderSong();							
							
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}else{
							view.setPadding(0, 0, 0, 0);
							view.setColorFilter(0x00000000, Mode.SRC_OVER);
						}
						return true;
					}
				});
				
				
				TextView btn_top_left_text = (TextView)activity.findViewById(R.id.btn_top_left_text);
				btn_top_left_text.setText("Edit");
				
				mFolderArr = (ArrayList<Folder>)result;					
				ListAdapter adapter = new FolderAdapter(activity.getApplicationContext(),mFolderArr);
				
				final ListView folder_list = (ListView)activity.findViewById(R.id.listv_folders);
				folder_list.setAdapter(adapter);
				
				// 폴더 상세 보기
				folder_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parentView, View view, int position, long id) {
						// TODO Auto-generated method stub
						
						// show folder detail
						Folder folder = (Folder)folder_list.getAdapter().getItem(position);
						
						if("0".equals(folder.getSong_count()) && "0".equals(folder.getFolder_id()) ){
							AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
							ab.setMessage("좋아요 폴더가 비어있습니다.\n곡 플레이중 좋아요 해주세요.");					
							ab.setPositiveButton("ok", null);  
							ab.show();
						}else if("0".equals(folder.getSong_count())){
							AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
							ab.setMessage("폴더에 플레이할 곡이 없습니다.\n선곡하기 버튼을 눌러 폴더에 곡을 넣어주세요");					
							ab.setPositiveButton("ok", null);  
							ab.show();
						}else{
							
							if("0".equals(folder.getFolder_id())){ // 라이크 폴더
								activity.folderDetailMd.showLikeFolderDetail(folder, null);
							}else{ // 일반폴더
								activity.folderDetailMd.showFolderDetail(folder, null);
							}							
						}												
					}					
				});
				
				ViewFlipper myViewFlipper = (ViewFlipper)activity.findViewById(R.id.flipper_layout);
				
				View fromView = myViewFlipper.getChildAt(0); // genre
				View toView = myViewFlipper.getChildAt(1); // studio
				
				
				AnimationFactory.flipTransition(myViewFlipper, fromView, toView, FlipDirection.RIGHT_LEFT);
//				AnimationFactory.flipTransition(myViewFlipper, FlipDirection.RIGHT_LEFT);
				
			}
			
			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub					
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);		
				
				// 사용자 정보를 셋팅
				activity.facebookMd.getUserInfo();

				HttpPost post = new HttpPost("http://14.63.217.155/radio_bonosound/folderListInfo.php");
//					uId : 유저 ID

				String userId = activity.facebookMd.getBonoUserId();
				
				if(userId == null || userId.length() < 1){
					throw new Exception("parameter error");
				}
				
//				Log.e("#########uId", "########" + userId);
				
				List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
				params.add(new BasicNameValuePair("uId", userId));
				
				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);  

				InputStream in = responsePOST.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				
				in.close();					
				String jsonStr = str.toString();
//				Log.e("#########result", "########" + jsonStr);				
				
				if(jsonStr != null && jsonStr.length() > 0){

					ArrayList<Folder> folderArr = new ArrayList<Folder>();
					JSONObject jsonObj = new JSONObject(jsonStr); 
					JSONArray resultArray = jsonObj.getJSONArray("result");

					for (int i = 0; i < resultArray.length(); i++) {
						Folder folder = new Folder();
						JSONObject jObj = resultArray.getJSONObject(i);
						folder.setFolder_id(jObj.getString("folder_id").toString());
						folder.setTitle(jObj.getString("title").toString());
						folder.setSong_count(jObj.getString("song_count").toString());
						folder.setType(jObj.getString("type").toString());
						folderArr.add(folder);
					}					
					resultSet.setResult(folderArr);	
				}
			}
		}).start(); 
	}


	@Override
	public void backMd() {
		// TODO Auto-generated method stub
		activity.genreMd.showGenreList();		
	}

}
